package com.atguigu.gulimall.ware.service.impl;

import com.atguigu.common.constant.WareConstant;
import com.atguigu.common.exception.RRException;
import com.atguigu.gulimall.ware.entity.PurchaseDetailEntity;
import com.atguigu.gulimall.ware.entity.vo.MergeVo;
import com.atguigu.gulimall.ware.entity.vo.PurchaseDoneItemVo;
import com.atguigu.gulimall.ware.entity.vo.PurchaseDoneVo;
import com.atguigu.gulimall.ware.service.PurchaseDetailService;
import com.atguigu.gulimall.ware.service.WareSkuService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.ware.dao.PurchaseDao;
import com.atguigu.gulimall.ware.entity.PurchaseEntity;
import com.atguigu.gulimall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.constraints.NotNull;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    PurchaseDetailService purchaseDetailService;

    @Autowired
    WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public boolean savePurchase(PurchaseEntity purchase) {
        purchase.setCreateTime(new Date());
        purchase.setUpdateTime(new Date());
        purchase.setAmount(new BigDecimal(0));
        this.baseMapper.insert(purchase);
        return true;
    }

    @Override
    public PageUtils queryPageUnreceivePurchase(Map<String, Object> params) {
        LambdaQueryWrapper<PurchaseEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PurchaseEntity::getStatus, 0).or().eq(PurchaseEntity::getStatus, 1);

        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params), queryWrapper);

        return new PageUtils(page);
    }

    @Override
    @Transactional
    public boolean mergePurchase(MergeVo mergeVo) {
        Long purchaseId = mergeVo.getPurchaseId();
        //没有发送采购单ID
        if (purchaseId == null) {
            //新建一个采购单
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATE.getCode());
            purchaseEntity.setPriority(10);
            this.savePurchase(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }

        //修改采购需求的分配状态和所属采购单
        List<Long> ids = mergeVo.getItems();
        Long finalPurchaseId = purchaseId;
        //映射出需要修改的部分：采购项对应的采购单、采购项状态
        List<PurchaseDetailEntity> detailEntities = ids.stream().map(id -> {
            //确认采购项是否可以合并（采购项状态为0或1才可合并）
            PurchaseDetailEntity entity = purchaseDetailService.getById(id);
            if (entity.getStatus() != WareConstant.PurchaseDetailStatusEnum.CREATE.getCode()
                    && entity.getStatus() != WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode()) {
                throw new RRException("存在不可被分配的采购项");
            }

            //设置需要修改的部分
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            detailEntity.setId(id);
            detailEntity.setPurchaseId(finalPurchaseId);
            detailEntity.setSkuPrice(entity.getSkuPrice()); //用于实现累加计算总价
            detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
            return detailEntity;
        }).collect(Collectors.toList());

        purchaseDetailService.updateBatchById(detailEntities);

        //更新修改时间和总金额
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseId);
        purchaseEntity.setUpdateTime(new Date());
        BigDecimal amount = new BigDecimal(0);
        for (PurchaseDetailEntity detailEntity : detailEntities) {
            amount = amount.add(detailEntity.getSkuPrice());
        }
        purchaseEntity.setAmount(amount);
        this.updateById(purchaseEntity);

        return true;
    }

    @Override
    @Transactional
    public boolean receivedPurchase(List<Long> ids) {
        //确认当前采购单是新建或者已分配
        List<PurchaseEntity> purchaseEntities = ids.stream().map(id -> {
            //根据id查询出对应的采购单对象
            return this.getById(id);
        }).filter(item -> {
            //过滤出新建或者已分配的采购单
            if (item.getStatus() == WareConstant.PurchaseStatusEnum.CREATE.getCode() ||
                    item.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()) {
                return true;
            }
            return false;
        }).map(purchaseEntity -> {
            //更改采购单的状态和修改时间
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
            purchaseEntity.setUpdateTime(new Date());
            return purchaseEntity;
        }).collect(Collectors.toList());

        //改变采购单的状态
        this.updateBatchById(purchaseEntities);

        //改变被领取的采购单中所有采购项的状态
        purchaseEntities.forEach(item -> {
            //根据采购单id查找此采购单中的所有采购项
            List<PurchaseDetailEntity> detailEntities = purchaseDetailService.listDetailByPurchaseId(item.getId());
            //映射出需要修改的部分：采购项的状态
            List<PurchaseDetailEntity> collect = detailEntities.stream().map(detailEntity -> {
                PurchaseDetailEntity entity = new PurchaseDetailEntity();
                entity.setId(detailEntity.getId());
                entity.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
                return entity;
            }).collect(Collectors.toList());
            //根据id批量修改采购项的状态
            purchaseDetailService.updateBatchById(collect);
        });

        return true;
    }

    @Override
    public boolean purchaseDone(PurchaseDoneVo purchaseDoneVo) {
        //1、改变采购项状态
        boolean flag = true;        //标志采购单采购是否成功
        List<PurchaseDetailEntity> collect = new ArrayList<>();    //存储所有采购项需要修改的内容

        List<PurchaseDoneItemVo> items = purchaseDoneVo.getItems();
        for (PurchaseDoneItemVo item : items) {
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();

            //如果有采购项采购失败 --> 采购单采购有错误
            if(item.getStatus() == WareConstant.PurchaseDetailStatusEnum.ERROR.getCode()){
                flag = false;
            } else {
                //3、将成功采购的进行入库
                PurchaseDetailEntity successEntity = purchaseDetailService.getById(item.getItemId());
                wareSkuService.addStock(successEntity.getSkuId(), successEntity.getWareId(), successEntity.getSkuNum());
            }

            //设置需要修改的内容：采购项状态
            detailEntity.setStatus(item.getStatus());
            detailEntity.setId(item.getItemId());

            collect.add(detailEntity);
        }
        purchaseDetailService.updateBatchById(collect);

        //2、改变采购单状态
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseDoneVo.getId());
        purchaseEntity.setUpdateTime(new Date());
        if(flag){
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.FINISH.getCode());
        } else {
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.ERROR.getCode());
        }
        this.updateById(purchaseEntity);

        return true;
    }

}